<?php

class db {
	private $host;
	private $port;
	private $user;
	private $pass;
	private $db_name="fashion";
	private $ln;
	/*
	 * OK : return 0
	 * NG : return -1
	 * 
	 * param:
	 * type , 1:normal , 2:persistant(keep connection)
	 */
	function con($type=1){
		try{
			//connection
			//@ is that if error case, don't display error message
			switch($type){
				case 1:$this->ln=@mysql_connect('localhost:8889', 'root', 'root');break;
				case 2:$this->ln=@mysql_pconnect('localhost', 'root', 'root');break;
				default:return -1;
			}
			if($this->ln==false){
				return -1;
			}
			mysql_select_db($this->db_name);
			mysql_query('SET NAMES utf8');
		}catch(Exception $e) {
			return -1;
		}
		return 0;
	}
	function cls(){
		try{
			mysql_close($this->ln);
		}catch(Exception $e) {
			return -1;
		}
		return 0;
	}
	function tran(){
		return $this->execute('START TRANSACTION;');
	}
	function commit(){
		return $this->execute('COMMIT;');
	}
	/*
	 * OK : return result
	 * NG : return -1
	 * 
	 * param:
	 * query: string
	 */
	function execute($query){
		$res=null;
		if(!$this->ln){return -1;}
		try{
			//execute query
			$res=mysql_query($query,$this->ln);
		}catch(Exception $e) {
			return -1;
		}
		return $res;
	}
	function sel($q){return $this->execute($q);}
	function ins($tbl,$vals){
		$q='insert into '.$tbl.' values '.$vals.';';
		return $this->execute($q);
	}
	function upd($q){return $this->execute($q);}
	function del($q){return $this->execute($q);}
	function sel_param($tbl, $cols = array(), $wheres = array()){
		/*
		 * $tbl    : string
		 * $cols   : array
		 * $wheres : array
		 */
		$q = 'select '.$this->makeCols($cols).' from '.$tbl.$this->makeWhere($wheres).';';
		
		print "<br />".$q."<br />";
		//execute
		return $this->execute($q);
	}
	//////////////////////////////////////////////////////////
	// Util
	//////////////////////////////////////////////////////////
	function makeCols($cols){
		if(count($cols)<=0)return '*';
		$c = '';
		foreach ($cols as $k => $v) {
			if(strlen($c)>0)$c.=', ';
			//$k : number, $v : column name
			$c.=$v;
		}
		return $c;
	}
	function makeWhere($wheres){
		if(count($wheres)<=0)return '';
		$w = '';
		foreach ($wheres as $k => $v) {
			if(strlen($w)>0)$w.=' and ';
			//$k : column name, $v : terms and value
			$w.=$k.'='.$this->makeAsChar($v);
		}
		return ' where '.$w;
	}
	function makeAsChar($p){
		return "'".$p."'";
	}
	function getAsJSON($res){
		$a=array();
		while($row=mysql_fetch_assoc($res)){
			array_push($a,$row);
		}
		return json_encode($a);
	}
}
/*
$test = new db();
$test->con();
if($test->tran()){
	if(!$test->ins('item',"('999','bbd')")){
		print('insert error'.mysql_error());
	}
	$test->commit();
}
$res=$test->sel_param('item',array('id'),array('id'=>'de'));
print($test->getAsJSON($res));
$test->cls();
